<?php 

class Utils{
	
	function getLimit(){
		$page = $_POST['page'];
		$rp = $_POST['rows'];
		if (!$page) 
			$page = 1;
		if (!$rp) 
			$rp = 10;
		
		$start = (($page-1) * $rp);
		$limit = "LIMIT $start, $rp";
		
		return $limit;
	}
	
	function getSort(){
		$sortname = $_POST['sort'];
		$sortorder = $_POST['order'];
		if (!$sortname) {
			return "";
		}
		if (!$sortorder) $sortorder = 'desc';
		$sort = "ORDER BY $sortname $sortorder";
		return $sort;
	}


	function getBusqueda(){
		
	}
	

	function for_decremental(){
		for($i=5; $i>=0; $i=$i-1){
			echo $i." ";
		}
	}
	
	/**
	 * Retorna el numero de dies entre dues dates passades en format dd/mm/yyyy o dd-mm-yyyy
	 *
	 * @param unknown_type $dFecIni
	 * @param unknown_type $dFecFin
	 * @return unknown
	 */
	function getDiesEntreFechas($dFecIni, $dFecFin){
		$dFecIni = str_replace("-","",$dFecIni);
		$dFecIni = str_replace("/","",$dFecIni);
		$dFecFin = str_replace("-","",$dFecFin);
		$dFecFin = str_replace("/","",$dFecFin);
		ereg( "([0-9]{1,2})([0-9]{1,2})([0-9]{2,4})", $dFecIni, $aFecIni);
		ereg( "([0-9]{1,2})([0-9]{1,2})([0-9]{2,4})", $dFecFin, $aFecFin);
		$date1 = mktime(0,0,0,$aFecIni[2], $aFecIni[1], $aFecIni[3]);
		$date2 = mktime(0,0,0,$aFecFin[2], $aFecFin[1], $aFecFin[3]);
		return round(($date2 - $date1) / (60 * 60 * 24));
	}
	
	/**
	 * Devuelve una fecha resultado de una suma entre una  fecha sobre otra.
	 *
	 */
	function sumarXdiasData($dia,$mes,$año,$diesASumar){
		date_default_timezone_set('Europe/Madrid');
		$dateaux = date('Y-m-d', mktime(0,0,0,$mes, $dia+$diesASumar,$año));
		return $dateaux;
	}
	
	/**
	 * Probar
	 *
	 */
	function getDiaSetmana($data){
		$baseDades = new BaseDades();
		$bd = $baseDades->getInstancia(DSN);
		$queryString = "SELECT WEEKDAY('".$data."') AS DIA";
		$rs = $bd->query($queryString);
		if ($rs) {
			$diaSetmana = $rs->fields[DIA];
			$rs->close();
			unset($rs);
			return $diaSetmana;
		}
		unset($rs);
		return -1;
	}
	
	function formatDataSQL($array){
		$mes=substr($array, 4, 4);
		$dia=substr($array, 8, 2);
		$any=substr($array, 0, 4);
		$data=$dia.$mes.$any;
		return $data;
	}

	function id_unica(){
		return md5(time() . mt_rand(1,1000000));  
	}
	
	function minusculas($str) {
		return strtolower($str);
	}
	
	function mayusculas($str) {
		return strtoupper($str);
	}
	
	function alfabetoAZ(){
		foreach (range('A', 'Z') as $letter) {
			echo $letter;
		}
	}
	
	
	/*
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 * A PROBAR
	 * A PROBAR
	 * A PROBAR
	 * A PROBAR 
	 * A PROBAR
	 * A PROBAR 
	 * 
	
	
	
	
	function getDiesEntreDates($dFecIni, $dFecFin){
		$dFecIni = str_replace("-","",$dFecIni);
		$dFecIni = str_replace("/","",$dFecIni);
		$dFecFin = str_replace("-","",$dFecFin);
		$dFecFin = str_replace("/","",$dFecFin);
		ereg( "([0-9]{1,2})([0-9]{1,2})([0-9]{2,4})", $dFecIni, $aFecIni);
		ereg( "([0-9]{1,2})([0-9]{1,2})([0-9]{2,4})", $dFecFin, $aFecFin);
		$date1 = mktime(0,0,0,$aFecIni[2], $aFecIni[1], $aFecIni[3]);
		$date2 = mktime(0,0,0,$aFecFin[2], $aFecFin[1], $aFecFin[3]);
		return round(($date2 - $date1) / (60 * 60 * 24));
	}
	
	function sumarXdiesData($dia,$mes,$any,$diesASumar){
		date_default_timezone_set('Europe/Madrid');
		$dateaux = date('Y-m-d', mktime(0,0,0,$mes, $dia+$diesASumar, $any));
		return $dateaux;
	}
	
	function getDiaSetmana($data){
		$baseDades = new BaseDades();
		$bd = $baseDades->getInstancia(DSN);
		$queryString = "SELECT WEEKDAY('".$data."') AS DIA";
		$rs = $bd->query($queryString);
		if ($rs) {
			$diaSetmana = $rs->fields[DIA];
			$rs->close();
			unset($rs);
			return $diaSetmana;
		}
		unset($rs);
		return -1;
	}
	
	function getPrimerDiaSetmana($data){
		$diaSetmana = $this->getDiaSetmana($data);
		$primerDiaSetmana = mktime(0,0,0,date("m"),date("d")-$diaSetmana,date("Y"));
		$primerDiaSetmana = date("Y/m/d", $primerDiaSetmana);
		return $primerDiaSetmana;
	}
	
	function getSumarUnDia($data){
		$dateTime = new DateTime($data);
		$dateTime->modify("+"."1"." day");
		return $dateTime->format("Y-m-d");
	}
	
	function getUltimDiaSetmana($date){
		$diaSetmana = $this->getDiaSetmana($date);
		$diesAfegir=6-$diaSetmana;
		$ultimDiaSetmana = mktime(0,0,0,date("m"),date("d")+$diesAfegir,date("Y"));
		$ultimDiaSetmana = date("Y/m/d", $ultimDiaSetmana);
		return $ultimDiaSetmana;
	}
	
	
	function formatHora($data){
	
		$hora=substr($data,11,12);
		$hora=substr($hora,0,5);
		return $hora;
	}
	
	function formatData($data){
		$diaData=substr($data,0,2);
		$mesData=substr($data,3,2);
		$anyData=substr($data,6,4);
		$data=$anyData."-".$mesData."-".$diaData;
		return $data;
	}
	
	function formatDataSQL($array){
		$mes=substr($array, 4, 4);
		$dia=substr($array, 8, 2);
		$any=substr($array, 0, 4);
		$data=$dia.$mes.$any;
		return $data;
	}
	
	function changeData($array){
		$mes=substr($array, 4, 4);
		$dia=substr($array, 8, 2);
		$any=substr($array, 0, 4);
		$data =$dia.$mes.$any;
		$hora = substr($array, 10, 6);
		$info= array();
		$info['hora']=$hora;
		$info['data']=$data;
		return $info;
	}
	/ Retorna un objecte date si li passem un string de forma DD-MM-AAAA
	function retornaDataFromDD_MM_AAAA($data){
		$any=substr($data,6,4);
		$mes=substr($data,3,2);
		$dia=substr($data,0,2);
		return mktime(0, 0, 0, $dia, $mes, $any);
	}
	
	function cercarDatesNotificacioResultat($data_joc_real){
		$dates=array();
		$any=substr($data_joc_real,6,4);
		$mes=substr($data_joc_real,3,2);
		$dia=substr($data_joc_real,0,2);
		$dates['data_joc_real']=mktime(0, 0, 0, $dia, $mes, $any);
		$dates['data_actual'] = mktime(0, 0, 0, date("d"), date("m"), date("Y"));
		$dates['data_anterior'] = mktime(0, 0, 0, date("d")-3 , date("m"), date("Y"));
		return $dates;
	}
	
	function getDiaPerNumero($num){
		switch($num){
			case 0:
				return 'Dilluns';
			case 1:
				return 'Dimarts';
			case 2:
				return 'Dimecres';
			case 3:
				return 'Dijous';
			case 4:
				return 'Divendres';
			case 5:
				return 'Dissabte';
			case 6:
				return 'Diumenge';
		}
	
	}
	
	function calendari(){
		$mesos =  array ();
		$mesos[]= array('nom' => 'Gener','numero' => '01', 'url' => '($base . "/partits/calendari_club_mensual/" . $id_club . "/01");');
		$mesos[]= array('nom' => 'Febrer','numero' => '02', 'url' => '($base . "/partits/calendari_club_mensual/" . $id_club . "/02");');
		$mesos[]= array('nom' => 'Març','numero' => '03', 'url' => '($base . "/partits/calendari_club_mensual/" . $id_club . "/03");');
		$mesos[]= array('nom' => 'Abril','numero' => '04', 'url' => '($base . "/partits/calendari_club_mensual/" . $id_club . "/04");');
		$mesos[]= array('nom' => 'Maig','numero' => '05', 'url' => '($base . "/partits/calendari_club_mensual/" . $id_club . "/05");');
		$mesos[]= array('nom' => 'Juny','numero' => '06', 'url' => '($base . "/partits/calendari_club_mensual/" . $id_club . "/06");');
		$mesos[]= array('nom' => 'Juliol','numero' => '07', 'url' => '($base . "/partits/calendari_club_mensual/" . $id_club . "/07");');
		$mesos[]= array('nom' => 'Agost','numero' => '08', 'url' => '($base . "/partits/calendari_club_mensual/" . $id_club . "/08");');
		$mesos[]= array('nom' => 'Setembre', 'numero' => '09','url' => '($base . "/partits/calendari_club_mensual/" . $id_club . "/09");');
		$mesos[]= array('nom' => 'Octubre','numero' => '10', 'url' => '($base . "/partits/calendari_club_mensual/" . $id_club . "/10");');
		$mesos[]= array('nom' => 'Novembre','numero' => '11', 'url' => '($base . "/partits/calendari_club_mensual/" . $id_club . "/11");');
		$mesos[]= array('nom' => 'Desembre','numero' => '12', 'url' => '($base . "/partits/calendari_club_mensual/" . $id_club . "/12");');
		return $mesos;
	}
	
	private function inicialitzar(){
		$this->mesos =  array ();
		$this->mesos[0]= "gener" ;
		$this->mesos[1]= "febrer";
		$this->mesos[2]= "març";
		$this->mesos[3]= "abril";
		$this->mesos[4]= "maig";
		$this->mesos[5]= "juny";
		$this->mesos[6]= "juliol";
		$this->mesos[7]= "agost";
		$this->mesos[8]= "setembre";
		$this->mesos[9]= "octubre";
		$this->mesos[10]= "novembre";
		$this->mesos[11]= "desembre";
	
	}
	
	public function getNomMes($numero){
		return $this->mesos[$numero-1];
	}
	
	public function getNomMesApostrof($numero){
		if ($numero == 4 || $numero == 8 || $numero == 10 ){
			return "d'".$this->mesos[$numero-1];
		}
		return 'de '.$this->mesos[$numero-1];
	}
	
	
		function conf_init() {
		global $base_url, $base_path, $base_root, $url;

		// Export the following settings.php variables to the global namespace
		global $db_url, $db_prefix, $cookie_domain, $conf, $installed_profile;
		$conf = array();

		include_once './'. conf_path() .'/settings.php';

		if (isset($base_url)) {
			// Parse fixed base URL from settings.php.
			$parts = parse_url($base_url);
			if (!isset($parts['path'])) {
			$parts['path'] = '';
			}
			$base_path = $parts['path'] . '/';
			// Build $base_root (everything until first slash after "scheme://").
			$base_root = substr($base_url, 0, strlen($base_url) - strlen($parts['path']));
		}
		else {
			// Create base URL
			$base_root = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';

			// As $_SERVER['HTTP_HOST'] is user input, ensure it only contains
			// characters allowed in hostnames.
			$base_url = $base_root .= '://'. preg_replace('/[^a-z0-9-:._]/i', '', $_SERVER['HTTP_HOST']);

			// $_SERVER['SCRIPT_NAME'] can, in contrast to $_SERVER['PHP_SELF'], not
			// be modified by a visitor.
			if ($dir = trim(dirname($_SERVER['SCRIPT_NAME']), '\,/')) {
				$base_path = "/$dir";
				$base_url .= $base_path;
				$base_path .= '/';
			}
			else {
				$base_path = '/';
			}
		}

		if (!$cookie_domain) {
			// If the $cookie_domain is empty, try to use the session.cookie_domain.
			$cookie_domain = ini_get('session.cookie_domain');
		}
		if ($cookie_domain) {
			// If the user specifies the cookie domain, also use it for session name.
			$session_name = $cookie_domain;
		}
		else {
			// Otherwise use $base_url as session name, without the protocol
			// to use the same session identifiers across http and https.
			list( , $session_name) = explode('://', $base_url, 2);
			// We try to set the cookie domain to the hostname.
			// We escape the hostname because it can be modified by a visitor.
			if (!empty($_SERVER['HTTP_HOST'])) {
				$cookie_domain = check_plain($_SERVER['HTTP_HOST']);
			}
		}
		// Strip leading periods, www., and port numbers from cookie domain.
		$cookie_domain = ltrim($cookie_domain, '.');
		if (strpos($cookie_domain, 'www.') === 0) {
			$cookie_domain = substr($cookie_domain, 4);
		}
		$cookie_domain = explode(':', $cookie_domain);
		$cookie_domain = '.'. $cookie_domain[0];
		// Per RFC 2109, cookie domains must contain at least one dot other than the
		// first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
		if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
			ini_set('session.cookie_domain', $cookie_domain);
		}
		session_name('SESS'. md5($session_name));
	}

	function comptador_iniciar($nom) {
		global $comptadors;

		list($usec, $sec) = explode(' ', microtime());
		$comptadors[$nom]['inici'] = (float)$usec + (float)$sec;
		$comptadors[$nom]['num'] = isset($comptadors[$nom]['num']) ? ++$comptadors[$nom]['num'] : 1;
	}

	function comptador_llegir($nom) {
		global $comptadors;

		if (isset($comptadors[$nom]['inici'])) {
			list($usec, $sec) = explode(' ', microtime());
			$stop = (float)$usec + (float)$sec;
			$diff = round(($stop - $comptadors[$nom]['inici']) * 1, 4);

			if (isset($comptadors[$nom]['temps'])) {
				$diff += $comptadors[$nom]['temps'];
			}
			return $diff;
		}
	}

	function comptador_parar($nom) {
		global $comptadors;

		$comptadors[$nom]['temps'] = comptador_llegir($nom);
		unset($comptadors[$nom]['inici']);

		return $comptadors[$nom];
	}

	function request_uri() {
		foreach (array('HTTP_X_REWRITE_URL', 'REQUEST_URI', 'argv') as $var) {
			if ($uri = env($var)) {
				if ($var == 'argv') {
					$uri = $uri[0];
				}
				break;
			}
		}
		if (isset($_SERVER['REQUEST_URI'])) {
			$uri = $_SERVER['REQUEST_URI'];
		}
		else {
			if (isset($_SERVER['argv'])) {
				$uri = $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['argv'][0];
			}
			else {
				$uri = $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
			}
		}

		return $uri;
	}

	function referer_uri() {
		if (isset($_SERVER['HTTP_REFERER'])) {
			return $_SERVER['HTTP_REFERER'];
		}
	}

	function raphp_unset_globals() {
		if (ini_get('register_globals')) {
			$permes = array('_ENV' => 1, '_GET' => 1, '_POST' => 1, '_COOKIE' => 1, '_FILES' => 1, '_SERVER' => 1, '_REQUEST' => 1, 'GLOBALS' => 1);
			foreach ($GLOBALS as $clau => $valor) {
				if (!isset($permes[$clau])) {
					unset($GLOBALS[$clau]);
				}
			}
		}
	}

	function usa_objecte() {
		$args = func_get_args();
		foreach ($args as $fitxer) {
			if (strpos($fitxer, '.') !== false) {
				$params = explode('.', $fitxer);
				$fitxer = array_pop($params);
				$ruta = implode(SD, $params) . SD;
			}
			else {
				$ruta = '';
			}
			require_once(LIB_OBJECTES . $ruta . strtolower($fitxer) . '.php');
		}
	}
	
	function usa_vendor() {
		$args = func_get_args();
		foreach ($args as $fitxer) {
			require_once(LIB_VENDORS . strtolower($fitxer) . '.php');
		}
	}

	function ife($condition, $val1 = null, $val2 = null) {
		if (!empty($condition)) {
			return $val1;
		}
		return $val2;
	}

	function UTF8_mail($from, $to, $subject, $message, $tipus = 'text/html', $cc="", $bcc="") {
		$from = explode("<",$from );
		$headers = "From: =?UTF-8?B?".base64_encode($from[0])."?= <".$from[1]."\r\n";

		$to = explode("<",$to );
		$to = "=?UTF-8?B?".base64_encode($to[0])."?= <".$to[1];

		$subject = "=?UTF-8?B?".base64_encode($subject)."?=\n";

		if($cc!=""){
			$cc = explode("<",$cc );
			$headers .= "Cc: =?UTF-8?B?".base64_encode($cc[0])."?= <".$cc[1]."\r\n";
		}

		if($bcc!=""){
			$bcc = explode("<",$bcc );
			$headers .= "Bcc: =?UTF-8?B?".base64_encode($bcc[0])."?= <".$bcc[1]."\r\n";
		}

		$headers .=
			"Content-Type: ".$tipus."; "
			. "charset=UTF-8; format=flowed\n"
			. "MIME-Version: 1.0\n"
			. "Content-Transfer-Encoding: 8bit\n"
			. "X-Mailer: PHP\n";

		return mail($to, $subject, $message, $headers);
	}	
	
	function seems_utf8($Str) { # by bmorel at ssi dot fr
		for ($i=0; $i<strlen($Str); $i++) {
			if (ord($Str[$i]) < 0x80) continue; # 0bbbbbbb
			elseif ((ord($Str[$i]) & 0xE0) == 0xC0) $n=1; # 110bbbbb
			elseif ((ord($Str[$i]) & 0xF0) == 0xE0) $n=2; # 1110bbbb
			elseif ((ord($Str[$i]) & 0xF8) == 0xF0) $n=3; # 11110bbb
			elseif ((ord($Str[$i]) & 0xFC) == 0xF8) $n=4; # 111110bb
			elseif ((ord($Str[$i]) & 0xFE) == 0xFC) $n=5; # 1111110b
			else return false; # Does not match any model
			for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
				if ((++$i == strlen($Str)) || ((ord($Str[$i]) & 0xC0) != 0x80))
				return false;
			}
		}
		return true;
	}

	if(! function_exists('str_split')) {
		function str_split($text, $split = 1) {
			$array = array();
           
			for ($i = 0; $i < strlen($text);) {
				$array[] = substr($text, $i, $split);
				$i += $split;
			}
           
			return $array;
		}
	}
	/*
	function mysql_a_data($data){
			$anyData=substr($data,0,4);
			$mesData=substr($data,5,2);
			$diaData=substr($data,8,2);
			$returnValue=$diaData."-".$mesData."-".$anyData;
			return $returnValue;	
		
	}
	
	function mysql_a_data($fecha){
		ereg( "([0-9]{2,4})-([0-9]{1,2})-([0-9]{1,2})", $fecha, $mifecha);
		$lafecha=$mifecha[3]."/".$mifecha[2]."/".$mifecha[1];
		return $lafecha;
	}

	function mysql_a_hora($data){
		return substr($data, 11, 5);
	}
	function data_a_mysql($fecha){
		ereg( "([0-9]{1,2})/([0-9]{1,2})/([0-9]{2,4})", $fecha, $mifecha);
		$lafecha=$mifecha[3]."-".$mifecha[2]."-".$mifecha[1];
		return $lafecha;
	} 

	// Retorna el microtime pel temps d'execució @return float Microtime
	
	
	function getMicrotime() {
			if (!function_exists('getMicrotime')) {
			list($usec, $sec) = explode(" ", microtime());
			return ((float)$usec + (float)$sec);
		}
	}

						
	function stripslashes_profund($valor) {
		if (is_array($valor)) {
			$return = array_map('stripslashes_profund', $valor);
			return $return;
		} 
		else {
			$return = stripslashes($valor);
			return $return ;
		}
	}
	
	function e($text) {
		echo $text;
	}

	function minuscules($str) {
		return strtolower($str);
	}
	
	function majuscules($str) {
		return strtoupper($str);
	}
	
	function pr($var) {
		echo "<pre>";
		print_r($var);
		echo "</pre>";
	}

	function config() {
		$args = func_get_args();
		foreach ($args as $arg) {
			if (file_exists(APP_CONFIG . $arg . '.php')) {
				include_once(APP_CONFIG . $arg . '.php');

				if (count($args) == 1) {
					return true;
				}
			} else {
				if (count($args) == 1) {
					return false;
				}
			}
		}
		return true;
	}
	
	function t($string, $args = 0) {
		$string = Text::traduccio($string);
		if (!$args) {
			return $string;
		}
		else {
			// Transform arguments before inserting them
			foreach ($args as $key => $value) {
				switch ($key[0]) {
					// Escaped only
					case '@':
						$args[$key] = check_plain($value);
						break;
					// Escaped and placeholder
					case '%':
					default:
						$args[$key] = theme('placeholder', $value);
						break;
					// Pass-through
					case '!':
				}
			}
			return strtr($string, $args);
		}
	}

	
	
	Validate Email Address in PHP
	
	This validate Email address function will return boolean true or false
	
	function valid_email($address)
	{
		return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $address)) ? FALSE : TRUE;
	}
	
	
	Validate Multiple Email Addresses in PHP

	This function will validate multiple email addresses separated by comma. You have to use above function to achieve multiple email validation.
	
	
	function valid_emails($str)	{
			if (strpos($str, ',') === FALSE)
			{
				return valid_email(trim($str));
			}
	
			foreach (explode(',', $str) as $email)
			{
				if (trim($email) != '' && valid_email(trim($email)) === FALSE)
				{
					return FALSE;
				}
			}
		return TRUE;
	}
	
	
	Find Number of Days in a Month in PHP

	Takes a month/year as input and returns the number of days for the given month/year. Takes leap years into consideration.
	
	function find_days_in_month($month = 0, $year = '')	{
	
	  if ($month < 1 OR $month > 12) {
		  return 0;
	  }
	
	  if ( ! is_numeric($year) OR strlen($year) != 4)
	  {
		  $year = date('Y');
	  }
	
	  if ($month == 2)
	  {
		  if ($year % 400 == 0 OR ($year % 4 == 0 AND $year % 100 != 0))
		  {
			  return 29;
		  }
	  }
	
	  $days_in_month	= array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	  return $days_in_month[$month - 1];
	}
	
	//usage
	echo find_days_in_month(06, 2005);
	
	
	
	
	Converts a local Unix timestamp to GMT in PHP
	
	function local_to_gmt($time = '')
	{
	  if ($time == '')
		  $time = time();
	
	  return mktime( gmdate("H", $time), gmdate("i", $time), gmdate("s", $time), gmdate("m", $time), gmdate("d", $time), gmdate("Y", $time));
	}
	
	
	
	lista de todas las variables definidas, ya sean de entorno, servidor o las variables definidas por el usuario
	
	get_defined_vars();
	
	php_strip_whitespace()

	Devuelve el código fuente PHP en nombre_archivo, habiendo quitado los comentarios PHP y los espacios blancos
	
	*/
}

?>